package JDBC_1.util;

import org.apache.commons.dbutils.DbUtils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/5/11 21:10
 * @description： 获取数据库连接与资源的关闭
 */
public class JDBCUtils {
    public static Connection getConnection() throws Exception {
        //1.读取配置文件信息，定义一个输入流
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

        Properties pros = new Properties();
        pros.load(is);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");
        //2.加载驱动
        Class.forName(driverClass);
        //3.获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    public static void closeResourece(Connection connection, Statement ps){
        try {
            if (ps !=null)
                ps.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (connection!=null)
                connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public static void closeResourece(Connection connection, Statement ps,ResultSet rs){
        try {
            if (ps !=null)
                ps.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (connection!=null)
                connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }try {
            if (rs!=null)
                rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //用dbutils.jar中的dbutil操作类来实现
    public static void closeResourece1(Connection connection, Statement ps,ResultSet rs) {
       DbUtils.closeQuietly(connection);
       DbUtils.closeQuietly(rs);
       DbUtils.closeQuietly(ps);
    }
}
